package com.fan.chat.service.impl;

import com.fan.chat.component.ChatGPTStreamComponent;
import com.fan.chat.component.context.ChatContextHolder;
import com.fan.chat.controller.request.SseEmitterRequest;
import com.fan.chat.listener.CusSseStreamListener;
import com.fan.chat.service.ChatService;
import com.plexpt.chatgpt.ChatGPTStream;
import com.plexpt.chatgpt.entity.chat.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

@Slf4j
@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatGPTStreamComponent chatGPTStreamComponent;

    @Autowired
    private ChatContextHolder chatContextHolder;

    @Override
    public void context(SseEmitterRequest request) {
        chatContextHolder.addMessage(request.getId(), request.getContext());
    }

    @Override
    public SseEmitter sseEmitter(SseEmitterRequest request) {
        SseEmitter sseEmitter = new SseEmitter(-1L);

        List<Message> messages = chatContextHolder.getListMessage(request.getId());

        ChatGPTStream chatGPTStream = chatGPTStreamComponent.getChatGPTStream();
        chatGPTStream.streamChatCompletion(messages,
                new CusSseStreamListener(sseEmitter));
        return sseEmitter;
    }
}
